package com.tanhua.management.service;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.management.domain.User;
import com.tanhua.management.mapper.UserMapper;
import com.tanhua.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.Duration;
import java.util.concurrent.TimeUnit;

@Service
public class UserService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private UserMapper userMapper;

    public void getCaptchaCode(String uuid, HttpServletResponse response) throws IOException {
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(93, 46, 4, 100);
        String code = lineCaptcha.getCode();
        stringRedisTemplate.opsForValue().set("Captcha_Code_"+uuid, code, 10, TimeUnit.MINUTES);

        response.setContentType("image/jpg");
        lineCaptcha.write(response.getOutputStream());        //图片通过输出写出
    }

    public String login(String username, String password, String captcha, String uuid) {
        String str = stringRedisTemplate.opsForValue().get("Captcha_Code_" + uuid);
        if(str != null && !"".equals(captcha) && !"".equals(uuid) && captcha.equals(str)){
            //验证码正确
            stringRedisTemplate.delete("Captcha_Code_" + uuid);
            QueryWrapper<User> qr = new QueryWrapper<>();
            qr.eq("username",username);
            qr.eq("password", SecureUtil.md5(password));
            User user = userMapper.selectOne(qr);

            String token = JwtUtil.createToken(user, "tanhua-management");
            String json = JSON.toJSONString(user);

            stringRedisTemplate.opsForValue().set("Background_Token_"+token, json, Duration.ofDays(1));

            return token;
        }else {
            return null;
        }
    }

    public User isLogin(String token){
        String json = stringRedisTemplate.opsForValue().get("Background_Token_" + token);
        if(json == null){
            return null;
        }else{
            User user = JSON.parseObject(json, User.class);
            return user;
        }
    }
}
